# -*- coding: utf-8 -*-
"""
@File    : henan_security_session_verify
@Author  : caojy
@Time    : 24/12/17 16:30
"""
import re
from urllib.parse import urljoin

import requests
import scrapy
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy import Request
from scrapy.http import HtmlResponse


def stringToHex(string):
    length = len(string)
    hex_string = str()
    for i in range(length):
        hex_string += hex(ord(string[i]))[2:]
    return hex_string


def get_cookie(url):
    hex_string = stringToHex(url)
    cookie = {"srcurl": hex_string, "path": "/"}
    return cookie


class HenanSecuritySessionVerify(RetryMiddleware):

    def process_request(self, request, spider):
        return None

    def get_resonse(self, request, response):
        if 'YunSuoAutoJump' in response.text:
            url = request.url
            session = requests.Session()
            r = session.get(url)
            url_2 = re.compile(r"self\.location\s*=\s*\"(.*?)\"").findall(r.text)[0]
            screen_date = "1920,1080"
            url_2 = url_2 + stringToHex(screen_date)
            url_2 = urljoin(url, url_2)
            cookie = get_cookie(url)
            session.cookies.update(cookie)
            r2 = session.get(url_2)
            url3 = re.compile(r"self\.location\s*=\s*\"(.*?)\"").findall(r2.text)[0]
            r3 = session.get(url3)
            r3.encoding = "gbk"
            self.response = HtmlResponse(
                request.url,
                encoding=r3.encoding,
                status=r3.status_code,
                headers=response.headers,
                body=r3.content,
                request=request
            )
            return self.response
        return response

    def process_response(self, request, response, spider):
        response = self.get_resonse(request, response)
        return response
